#include "sd.h"
#include "stdio.h"
sdcard_t sdcard;
uint8_t sdcard_init()
{
    printf("sdcard_init.\r\n");
    clk_reset_set(CCU_BUS_SOFT_RST0, 8);
    clk_enable(CCU_BUS_CLK_GATE0, 8);
    clk_reset_clear(CCU_BUS_SOFT_RST0, 8);

    gpio_init(GPIOF, PIN1 | PIN2 | PIN3, GPIO_MODE_AF2, GPIO_PULL_NONE, GPIO_DRV_3);

    sdcard.sdc_base = SDC0_BASE;
    sdcard.voltage = MMC_VDD_27_36;
    sdcard.width = MMC_BUS_WIDTH_1;
    sdcard.clock = 50000000;

    if (sdcard_detect(&sdcard) == 1)
    {
        printf("sd detect OK.\r\n");
        return 0;
    }
    printf("sd detect fail.\r\n");
    return 1;
}

void sdcard_test()
{
    uint8_t write[512 * 10], read[512 * 10];
    for (int i = 0; i < 512 * 10; i++)
    {
        write[i] = i & 0xff;
        read[i] = 0;
    }
    sdcard_write(&sdcard, write, 200, 10);
    uint64_t blk_cnt = sdcard_read(&sdcard, read, 200, 10);
    printf("read blk_cnt:%lld \r\n", blk_cnt);

    for (int i = 0; i < 512; i++)
    {
        printf("%02X ", read[i]);
        if ((i + 1) % 32 == 0)
            printf("\r\n");

        if ((i + 1) % 512 == 0)
            printf("\r\n\r\n");
    }
}